<?php if ( ! defined('FCPATH')) exit('No direct script access allowed');
/**
* Gestion du cache du site
* @author Richard G
* @package Layout
*/
class MY_Cache
{

	private $CI;
	private $dir_cache;

	public function __construct()
	{
		$this->CI = & get_instance();
		$this->CI->config->load('my_site', true, true);
		$this->dir_cache = FCPATH.APPPATH;
		$this->dir_cache .= $this->CI->config->item('dir_cache', 'my_site')."/";
	}

	/**
	* 	Regarde si on le résultat de la requete en cache
	*/
	public function get($sKey, $sFct = null, $aParam = array(), $force = false, $sTime = 0, $sType = "mysql")
	{
		$file_cache = $this->dir_cache.$sType."/".crc32($sKey);
		$array = false;
		if(file_exists($file_cache) && !$force) {
			$result = file_get_contents($file_cache);
			$array = @unserialize($result);
		}
		if(empty($array['result']) || $array['end'] < time()) {
			if($sFct !== null) {
				$result = call_user_func_array($sFct, $aParam);
				if(!empty($result)) {
					self::set($sKey, $result, $sTime, $sType);
				}
				return $result;
			}
			return array();
		}
		return $array['result'];
	}

	/**
	* 	Sauvegarde le resultat de la requete
	*/
	public function set($sKey, $aResult, $sTime = 0, $sType = "mysql")
	{
		$file_cache = $this->dir_cache.$sType."/".crc32($sKey);
		if($sTime == 0) {
			$sTime = $this->CI->config->item('time_cache', 'my_site');
		}
		$aSave = array(
					'key' => $sKey,
					'end' => (time()+$sTime),
					'result' => $aResult
				);
		$sSave = serialize($aSave);
		file_put_contents($file_cache, $sSave);
	}

	/**
	* 	Regarde si on le résultat de la requete en cache
	*/
	public function delete($sKey, $sType = "mysql")
	{
		$file_cache = $this->dir_cache.$sType."/".crc32($sKey);
		if(file_exists($file_cache)) {
			unlink($file_cache);
		}
	}

}